import {
  downloadTemplate,
  getColorTextLoadMap,
  getFileNameByPath,
  getTenantID,
  onMouseOutBtn,
  removeDateHmsStr,
  priceFormat,
  getPosIDs,
  getUserID,
} from '@/utils';
import { Button, Form, Input, InputNumber, Select, Tooltip, message, DatePicker, Slider, Switch, AutoComplete } from 'antd';
import Cls from 'classnames';
import { UploadFormCommon } from '@/components/UploadForm';
import { FormInstance } from 'antd/es/form/Form';
import {
  PlusCircleOutlined,
  AppstoreAddOutlined,
  QuestionCircleOutlined,
  DeleteOutlined,
  UploadOutlined,
  DownloadOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { ILoadMapTypeAll } from '@/common';
import moment from 'moment';
import { float_add } from './useMyUtil';
import { RegularExpression } from '@/common/constVariable';

const TodayDatePicker: any = DatePicker;

/** 处理数据 */
const handleMaterialCombined = (formName: FormInstance, fomIndex: number, currentValue: any, formType: string) => {
  const materialFormValues: Record<string, any>[] = formName?.getFieldValue('detailList');
  const currentSum: number = materialFormValues?.[fomIndex]?.[formType] || 0;
  const newPaymen = currentSum * currentValue;
  materialFormValues[fomIndex]['sumInTax'] = newPaymen;
  formName?.setFieldsValue({
    detailList: materialFormValues,
  });
};

/** 处理标的类别 */
const handleMaterialSupply = (formName: FormInstance, fomIndex: number) => {
  const materialFormValues: Record<string, any>[] = formName?.getFieldValue('detailList');
  materialFormValues[fomIndex]['supplyType'] = null;
  formName?.setFieldsValue({
    detailList: materialFormValues,
  });
};

/** 供货清单 new */
const getMaterialTableConfig = (
  addMaterialCallback: () => void,
  delMaterialCallback: (resObj: Record<string, any>) => void,
  formName: FormInstance,
  loadMapInfo: Record<string, any>,
  pageType: string,
  openCheckMaterial: (bool: boolean) => void,
  materialImport: () => void,
  materialExport: () => void,
): Record<string, any>[] => {
  /** 处理税率对象 */
  const taxRateInfoHand = () => {
    let taxRateInfo: Record<string, any> = {};
    loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.COMPANY_TAXRATE}`]?.forEach((item: any) => {
      if (item?.name) {
        taxRateInfo[Number(item?.name)] = item?.name;
      }
    });
    return taxRateInfo;
  };

  const tableConfig: Record<string, any>[] = [
    {
      title: <div style={{ textAlign: 'center' }}>序号</div>,
      dataIndex: 'modifyFlag',
      key: 'modifyFlag',
      visible: true,
      width: 70,
      fixed: 'left',
      render: (_text: string, _record: any, index: any) => {
        return (
          <>
            <div style={{ textAlign: 'center' }}>{index + 1}</div>
            <Form.Item name={['detailList', index, 'modifyFlag']} style={{ display: 'none' }}>
              <Input hidden />
            </Form.Item>
          </>
        );
      },
    },
    {
      title: '标的类别',
      dataIndex: 'supplyType',
      key: 'supplyType',
      visible: true,
      width: 160,
      fixed: 'left',
      require: true,
      render: (text: string, record: any, index: any) => {
        const hwList: any = [];
        const fwList: any = [];
        (loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`] || []).forEach((item) => {
          if (item.id == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1001` || item.id == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1002`) {
            fwList.push(item);
          } else {
            if (item.children && item.children.length) {
              item.children.map((element) => {
                hwList.push(element);
              });
            }
          }
        });
        if (text == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000`) {
          handleMaterialSupply(formName, index);
        }
        return (
          <Form.Item name={['detailList', index, 'supplyType']} rules={[{ required: true, message: '请选择标的类别' }]}>
            <Select placeholder="请选择" disabled={pageType == 'detail' ? true : false} showArrow={pageType == 'detail' ? false : true}>
              {(record.materialID ? hwList : fwList).map((item: any) => {
                return (
                  <Select.Option key={item?.id} value={item?.id}>
                    {item?.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        );
        // }
      },
    },
    {
      title: '分项名称',
      dataIndex: 'materialName',
      key: 'materialName',
      visible: true,
      width: 190,
      fixed: 'left',
      render: (text: string, _record: any, index: number) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'materialName']}>
              <Tooltip title={text}>
                <span>{text || '--'}</span>
              </Tooltip>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'materialName']} rules={[{ required: true, message: '请输入分项名称' }]}>
              <Input placeholder="请输入" disabled={pageType == 'detail' ? true : false} />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '品牌',
      dataIndex: 'brandType',
      key: 'brandType',
      visible: true,
      width: 190,
      render: (text: string, record: any, index: any) => {
        return (
          // <Form.Item name={['detailList', index, 'brandType']}>
          //   <Select
          //     placeholder="请选择"
          //     disabled={pageType == 'detail' ? true : false}
          //     showArrow={pageType == 'detail' ? false : true}
          //     showSearch
          //     optionFilterProp="children"
          //     fieldNames={{ label: 'name', value: 'id' }}
          //     filterOption={(input: string, option?: { label: string; value: string }) => {
          //       return (option?.name ?? '').includes(input);
          //     }}
          //     options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`] || []}
          //   />
          // </Form.Item>
          <Form.Item name={['detailList', index, 'brandType']}>
            <Input placeholder={pageType == 'detail' ? '--' : '请输入'} disabled={pageType == 'detail' ? true : false} />
          </Form.Item>
        );
      },
    },
    {
      title: '规格要求（参数）',
      dataIndex: 'specInfo',
      key: 'specInfo',
      visible: true,
      width: 260,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail' || _record.materialID) {
          return (
            <Form.Item name={['detailList', index, 'specInfo']}>
              <Tooltip title={text}>
                <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: '3', WebkitBoxOrient: 'vertical' }}>
                  {text || '--'}
                </div>
              </Tooltip>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'specInfo']}>
              <Input.TextArea
                placeholder="请输入"
                disabled={pageType == 'detail' ? true : false}
                showCount
                maxLength={800}
                autoSize={{
                  minRows: 2,
                  maxRows: 4,
                }}
              />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '数量',
      dataIndex: 'expectNum',
      key: 'expectNum',
      visible: true,
      width: 150,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'expectNum']}>
              <span>{text || '--'}</span>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'expectNum']} initialValue={0}>
              <InputNumber
                min={0}
                placeholder="请输入"
                disabled={pageType == 'detail' ? true : false}
                onChange={(value: any) => {
                  handleMaterialCombined(formName, index, value, 'priceInTax');
                }}
              />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '单位',
      dataIndex: 'unitBusinessName',
      key: 'unitBusinessName',
      visible: true,
      width: 150,
      render: (text: string, record: any, index: any) => {
        return (
          <Form.Item name={['detailList', index, 'unitBusinessName']}>
            <Select
              placeholder={pageType == 'detail' ? '--' : '请选择'}
              disabled={pageType == 'detail' ? true : false}
              showArrow={pageType == 'detail' ? false : true}
              showSearch
              optionFilterProp="children"
              fieldNames={{ label: 'name', value: 'id' }}
              filterOption={(input: string, option?: { label: string; value: string }) => {
                return (option?.name ?? '').includes(input);
              }}
              options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`] || []}
            />
          </Form.Item>
        );
      },
    },
    {
      title: '税率（%）',
      dataIndex: 'taxRate',
      key: 'taxRate',
      visible: true,
      width: 150,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'taxRate']}>
              <span>{text || '--'}</span>
            </Form.Item>
          );
        } else {
          const marks = taxRateInfoHand();
          const arr: any = [];
          Object.keys(marks)?.length &&
            Object.keys(marks).map((item) => {
              arr.push({
                label: item,
                value: item,
              });
            });
          return (
            <Form.Item name={['detailList', index, 'taxRate']} initialValue={0}>
              <AutoComplete
                options={arr}
                // style={{ width: 200 }}
                placeholder="请选择"
                disabled={pageType == 'detail' ? true : false}
              />
            </Form.Item>
          );
        }
      },
    },
    // {
    //   title: '税率（%）',
    //   dataIndex: 'taxRate',
    //   key: 'taxRate',
    //   visible: true,
    //   width: 150,
    //   render: (text: string, _record: any, index: any) => {
    //     if (pageType == 'detail') {
    //       return (
    //         <Form.Item name={['detailList', index, 'taxRate']}>
    //           <span>{text || '--'}</span>
    //         </Form.Item>
    //       );
    //     } else {
    //       const marks = taxRateInfoHand();
    //       const arr = Object.keys(marks) || [];
    //       return (
    //         <Form.Item name={['detailList', index, 'taxRate']} initialValue={0}>
    //           {/* <Slider disabled={pageType == 'detail' ? true : false} marks={marks} style={{ width: '95%' }} max={30} min={0} /> */}
    //           <Select placeholder="请选择" disabled={pageType == 'detail' ? true : false}>
    //             {arr.map((item: any) => {
    //               return (
    //                 <Select.Option key={item} value={item}>
    //                   {item}
    //                 </Select.Option>
    //               );
    //             })}
    //           </Select>
    //         </Form.Item>
    //       );
    //     }
    //   },
    // },
    {
      title: '含税单价（元）',
      dataIndex: 'priceInTax',
      key: 'priceInTax',
      visible: true,
      width: 150,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'priceInTax']}>
              <span>{text || '--'}</span>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'priceInTax']} initialValue={0}>
              <InputNumber
                min={0}
                placeholder="请输入"
                disabled={pageType == 'detail' ? true : false}
                onChange={(value: any) => {
                  handleMaterialCombined(formName, index, value, 'expectNum');
                }}
                step="0.01"
              />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '合价（元）',
      dataIndex: 'sumInTax',
      key: 'sumInTax',
      visible: true,
      width: 150,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'sumInTax']}>
              <span>{text || '--'}</span>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'sumInTax']} initialValue={0}>
              <InputNumber min={0} placeholder="自动带出" disabled step={0.01} />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '交付时间（非必填）',
      dataIndex: 'deliveryTime',
      key: 'deliveryTime',
      visible: true,
      width: 190,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'deliveryTime']}>
              <span>{removeDateHmsStr(text)}</span>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'deliveryTime']}>
              <TodayDatePicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM-DD" disabled={pageType == 'detail' ? true : false} />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '交付地点（非必填）',
      dataIndex: 'deliveryAddress',
      key: 'deliveryAddress',
      visible: true,
      width: 190,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'deliveryAddress']}>
              <Tooltip title={text}>
                <span>{text || '--'}</span>
              </Tooltip>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'deliveryAddress']}>
              <Input placeholder="请输入" disabled={pageType == 'detail' ? true : false} />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '交付方式（非必填）',
      dataIndex: 'deliveryStyle',
      key: 'deliveryStyle',
      visible: true,
      width: 190,
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['detailList', index, 'deliveryStyle']}>
              <Tooltip title={text}>
                <span>{text || '--'}</span>
              </Tooltip>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item name={['detailList', index, 'deliveryStyle']}>
              <Input placeholder="请输入" disabled={pageType == 'detail' ? true : false} />
            </Form.Item>
          );
        }
      },
    },
  ];

  // if (!(pageType == 'detail')) {
  tableConfig?.push({
    title: (
      <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        {!(pageType == 'detail') && (
          <>
            <Button
              type="link"
              size="small"
              icon={<PlusCircleOutlined />}
              className="manageBtntTxtStyle"
              onClick={addMaterialCallback}
              onMouseOut={onMouseOutBtn}
            >
              添加行
            </Button>
            <Button
              type="link"
              size="small"
              icon={<AppstoreAddOutlined />}
              className="manageBtntTxtStyle"
              onClick={() => {
                openCheckMaterial(true);
              }}
              onMouseOut={onMouseOutBtn}
            >
              选择
            </Button>
            {/* &nbsp;
            <Button type="link" size="small" icon={<DownloadOutlined />} className="manageBtntTxtStyle" onClick={materialImport} onMouseOut={onMouseOutBtn}>
              导入
            </Button>
            &nbsp; */}
          </>
        )}
        {/* <Button type="link" size="small" icon={<UploadOutlined />} className="manageBtntTxtStyle" onClick={materialExport} onMouseOut={onMouseOutBtn}>
          导出
        </Button> */}
      </div>
    ),
    dataIndex: 'otherBtn',
    key: 'otherBtn',
    width: !(pageType == 'detail') ? 140 : 120,
    // width: 100,
    fixed: 'right',
    render: (_text: any, record: any) => {
      return (
        <div className="counterpoartDelBtnStyle">
          {!(pageType == 'detail') ? (
            <Button
              type="link"
              size="small"
              icon={<DeleteOutlined />}
              className={Cls('manageBtntTxtStyle')}
              onMouseOut={onMouseOutBtn}
              onClick={() => {
                delMaterialCallback(record);
              }}
            >
              删除
            </Button>
          ) : (
            <span>--</span>
          )}
        </div>
      );
    },
  });
  // }

  return tableConfig;
};

/** 相关附件 */
const getFieldConfig = (
  formName: any,
  addFiledCallback: () => void,
  delFiledCallback: (resObj: Record<string, any>) => void,
  loadMapInfo: Record<string, any>,
  pageType: string,
  onFormChange: (values: Record<string, any>) => void,
  onOpenReadOfdWord: (fieldUrl: string) => void,
  setOpenAddAttachModal: (bool: boolean) => void,
  contractDetailInfo: Record<string, any>,
  curRes,
) => {
  const tableConfig: Record<string, any>[] = [
    {
      title: <div style={{ textAlign: 'center' }}>序号</div>,
      dataIndex: 'modifyFlag',
      key: 'modifyFlag',
      visible: true,
      width: 70,
      fixed: 'left',
      render: (_text: string, _record: any, index: any) => {
        return (
          <div>
            <div style={{ textAlign: 'center' }}>{index + 1}</div>
            <Form.Item name={['attachList', index, 'modifyFlag']} style={{ display: 'none' }}>
              <Input hidden />
            </Form.Item>
          </div>
        );
      },
    },
    {
      title: '附件类型',
      dataIndex: 'attachType',
      key: 'attachType',
      visible: true,
      width: 380,
      fixed: 'left',
      render: (text: string, _record: any, index: any) => {
        if (pageType == 'detail') {
          const textObj: Record<string, any> | any = loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_FIELDTYPE}`]?.find((item: any) => {
            return item?.id == text;
          });
          const { colorText } = getColorTextLoadMap(textObj?.name);
          return (
            <Form.Item name={['attachList', index, 'attachType']}>
              <span>{colorText || '--'}</span>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item
              name={['attachList', index, 'attachType']}
              rules={[
                {
                  required: true,
                  message: '请选择',
                },
              ]}
            >
              <Select placeholder="请选择" disabled={pageType == 'detail' ? true : false} showArrow={pageType == 'detail' ? false : true}>
                {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.CONTRACT_FIELDTYPE}`]?.map((item: any) => {
                  return (
                    <Select.Option key={item?.id} value={item?.id}>
                      {item?.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
          );
        }
      },
    },
    {
      title: '附件名称',
      dataIndex: 'attachName',
      key: 'attachName',
      visible: true,
      width: 380,
      // fixed: 'left',
      render: (text: string, _record: any, index: number) => {
        if (pageType == 'detail') {
          return (
            <Form.Item name={['attachList', index, 'attachName']}>
              <Tooltip title={text}>
                <span>{text || '--'}</span>
              </Tooltip>
            </Form.Item>
          );
        } else {
          return (
            <Form.Item
              name={['attachList', index, 'attachName']}
              rules={[
                {
                  required: true,
                  message: '请输入',
                },
              ]}
            >
              <Input placeholder="请输入" disabled={pageType == 'detail' ? true : false} />
            </Form.Item>
          );
        }
      },
    },
    {
      title: '附件',
      dataIndex: 'attachURL',
      key: 'attachURL',
      visible: true,
      // width: 190,
      // fixed: 'left',
      render: (_text: string, record: any, index: number) => {
        if (pageType == 'detail') {
          const contractName = record?.attachURL ? getFileNameByPath(record?.attachURL) : '';
          return (
            <Form.Item name={['attachList', index, 'attachURL']}>
              <div style={{ width: '100%' }}>
                {contractName ? (
                  <>
                    <a
                      onClick={() => {
                        downloadTemplate('/contractController/downloadFile', contractName, record?.attachURL, () => {});
                      }}
                    >
                      {contractName}
                    </a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <Tooltip title="在线预览">
                      <a
                        onClick={() => {
                          onOpenReadOfdWord(record?.attachURL);
                        }}
                      >
                        <EyeOutlined />
                      </a>
                    </Tooltip>
                  </>
                ) : (
                  <span>--</span>
                )}
              </div>
            </Form.Item>
          );
        } else {
          return (
            <UploadFormCommon
              form={formName}
              label=""
              // fileFormName={'contractURL'}
              fileFormName={['attachList', index, 'attachURL']}
              spanCol={24}
              inRowProportion={24}
              name={'attachFile'}
              required={true}
              accept={'.docx|.doc|.jpg|.jpeg|.png|.pdf'}
              url={'/contractController/uploadFile'}
              downloadUrl={'/contractController/downloadFile'}
              // fileFormDelName={['attachList', index, 'attachURLDel']}
              delFunc={() => {}}
              maxFile={1}
              defaultFiles={record?.id ? record?.attachURL : null}
              filedTypeTable={true}
              disabledUpload={pageType == 'detail' ? true : false}
              fieldBusiPath={'contract/info'}
              onChangeFormValues={onFormChange}
              isEdit={true}
              onOpenReadOfdWord={onOpenReadOfdWord}
            >
              上传附件
            </UploadFormCommon>
          );
        }
      },
    },
  ];
  if (!(pageType == 'detail')) {
    tableConfig?.push({
      title: (
        <div style={{ width: '100%', textAlign: 'center' }}>
          <Button type="link" size="small" icon={<PlusCircleOutlined />} className="manageBtntTxtStyle" onClick={addFiledCallback} onMouseOut={onMouseOutBtn}>
            添加
          </Button>
        </div>
      ),
      dataIndex: 'otherBtn',
      key: 'otherBtn',
      width: 100,
      fixed: 'right',
      render: (_text: any, record: any) => {
        return (
          <div className="counterpoartDelBtnStyle">
            <Button
              type="link"
              size="small"
              icon={<DeleteOutlined />}
              className={Cls('manageBtntTxtStyle')}
              onMouseOut={onMouseOutBtn}
              onClick={() => {
                delFiledCallback(record);
              }}
            >
              删除
            </Button>
          </div>
        );
      },
    });
  } else if (pageType == 'detail') {
    let arr = [
      `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1005`,
      `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1006`,
      `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1007`,
    ];
    let isHave: boolean = arr?.some((item: any) => {
      return item == contractDetailInfo?.state;
    });
    if (isHave) return;
    if (!(curRes?.['/contractController/edit'] && contractDetailInfo?.createPositionID == getPosIDs() && contractDetailInfo?.ownerID == getUserID())) return;
    //打开添加的弹窗modal
    tableConfig?.push({
      title: (
        <div style={{ width: '100%', textAlign: 'center' }}>
          <Button
            type="link"
            size="small"
            icon={<PlusCircleOutlined />}
            className="manageBtntTxtStyle"
            onClick={setOpenAddAttachModal}
            onMouseOut={onMouseOutBtn}
          >
            添加
          </Button>
        </div>
      ),
      dataIndex: 'otherBtn',
      key: 'otherBtn',
      width: 100,
      fixed: 'right',
    });
  }

  return tableConfig;
};

/** 付款信息 */
const getKeyNodesTableConfig = (
  paymentSty: string,
  addProgress: () => void,
  delProgressPay: (delRes: Record<string, any>) => void,
  formName: FormInstance,
  pageType: string,
  locationState: Record<string, any>,
): Record<string, any>[] => {
  const pamTypeKeys: any[] = [0, 1, 3, 4];

  const payStyFlag: boolean = paymentSty == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1001`;

  const special = paymentSty == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002` ? true : false;
  let tableConfig: Record<string, any>[];
  if (special) {
    tableConfig = [
      {
        title: <div style={{ textAlign: 'center' }}>序号</div>,
        dataIndex: 'modifyFlag',
        key: 'modifyFlag',
        visible: true,
        width: 70,
        fixed: 'left',
        render: (_text: string, _record: any, index: any) => {
          return (
            <>
              <div style={{ textAlign: 'center' }}>{index + 1}</div>
              <Form.Item name={['processList', index, 'modifyFlag']} style={{ display: 'none' }}>
                <Input hidden />
              </Form.Item>
            </>
          );
        },
      },
      {
        title: '履约事项',
        dataIndex: 'payExplain',
        key: 'payExplain',
        visible: true,
        width: 450,
        render: (text: string, record: any, index: any) => {
          const disabled: boolean = record?.payFinishSum && record?.payFinishSum > 0 ? true : false;

          if (pageType == 'detail') {
            return (
              <Form.Item name={['processList', index, 'payExplain']}>
                <Tooltip title={text}>
                  <span>{text || '--'}</span>
                </Tooltip>
              </Form.Item>
            );
          } else {
            return (
              <Form.Item
                name={['processList', index, 'payExplain']}
                rules={[
                  {
                    required: true,
                    message: '请输入',
                  },
                ]}
              >
                <Input.TextArea
                  allowClear
                  showCount
                  maxLength={500}
                  placeholder="请输入"
                  autoSize={{ minRows: 1, maxRows: 3 }}
                  disabled={pageType == 'detail' ? true : disabled ? true : false}
                />
              </Form.Item>
            );
          }
        },
      },
    ];
  } else {
    tableConfig = [
      {
        title: <div style={{ textAlign: 'center' }}>序号</div>,
        dataIndex: 'modifyFlag',
        key: 'modifyFlag',
        visible: true,
        width: 70,
        fixed: 'left',
        render: (_text: string, _record: any, index: any) => {
          return (
            <>
              <div style={{ textAlign: 'center' }}>{index + 1}</div>
              <Form.Item name={['processList', index, 'modifyFlag']} style={{ display: 'none' }}>
                <Input hidden />
              </Form.Item>
            </>
          );
        },
      },
      {
        title: '预期时间',
        dataIndex: 'payTime',
        key: 'payTime',
        visible: true,
        width: 180,
        render: (text: string, record: any, index: any) => {
          const disabled: boolean = record?.payFinishSum && record?.payFinishSum > 0 ? true : false;

          if (pageType == 'detail') {
            return (
              <Form.Item name={['processList', index, 'payTime']}>
                <span>{removeDateHmsStr(text)}</span>
              </Form.Item>
            );
          } else {
            //原合同判断是否在预计开始时间，预计结束时间之间
            let range = ['preBeginTime', 'preFinishTime'];
            let tip = ['预期时间不能早于预计开始时间，请修改。', '预期时间不能晚于预计结束时间，请修改。'];
            //补录时判断合同签订时间和合同截止时间
            if (locationState?.updateType == 'UpdateRepairAdd') {
              range = ['realBeginTime', 'realFinishTime'];
              tip = ['预期时间不能早于合同签订时间，请修改。', '预期时间不能晚于合同截止时间，请修改。'];
            }
            return (
              <Form.Item
                name={['processList', index, 'payTime']}
                dependencies={range}
                rules={[
                  {
                    required: true,
                    message: '请选择',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!getFieldValue(range[0])) {
                        return Promise.resolve();
                      }
                      if (!getFieldValue(range[1])) {
                        return Promise.resolve();
                      }
                      if (moment(value)?.isBefore(moment(getFieldValue(range[0])))) {
                        return Promise.reject(new Error(tip[0]));
                      }
                      if (moment(value)?.isAfter(moment(getFieldValue(range[1])))) {
                        return Promise.reject(new Error(tip[1]));
                      }
                      return Promise.resolve();
                    },
                  }),
                ]}
              >
                <TodayDatePicker
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                  // 暂时隐藏预期时间限制范围
                  // disabledDate={(currentDate: any) => {
                  //   return currentDate && currentDate < moment();
                  // }}
                  disabled={pageType == 'detail' ? true : disabled ? true : false}
                />
              </Form.Item>
            );
          }
        },
      },
      {
        title: '履约事项',
        dataIndex: 'payExplain',
        key: 'payExplain',
        visible: true,
        width: 250,
        render: (text: string, record: any, index: any) => {
          const disabled: boolean = record?.payFinishSum && record?.payFinishSum > 0 ? true : false;

          if (pageType == 'detail') {
            return (
              <Form.Item name={['processList', index, 'payExplain']}>
                <Tooltip title={text}>
                  <span>{text || '--'}</span>
                </Tooltip>
              </Form.Item>
            );
          } else {
            return (
              <Form.Item
                name={['processList', index, 'payExplain']}
                rules={[
                  {
                    required: true,
                    message: '请输入',
                  },
                ]}
              >
                <Input.TextArea
                  allowClear
                  showCount
                  maxLength={500}
                  placeholder="请输入"
                  autoSize={{ minRows: 1, maxRows: 3 }}
                  disabled={pageType == 'detail' ? true : disabled ? true : false}
                />
              </Form.Item>
            );
          }
        },
      },
      {
        title: '是否涉及款项',
        dataIndex: 'payFlag',
        key: 'payFlag',
        visible: true,
        width: 160,
        render: (text: string, record: any, index: any) => {
          const disabledFlag: boolean = payStyFlag ? (record?.payType == 2 || record?.payType == 5 ? true : false) : false;
          const disabled: boolean = record?.payFinishSum && record?.payFinishSum > 0 ? true : false;

          if (pageType == 'detail') {
            return (
              <Form.Item name={['processList', index, 'payFlag']}>
                <span>{text == '1' ? '是' : text == '0' ? '否' : '--'}</span>
              </Form.Item>
            );
          } else {
            return (
              <Form.Item name={['processList', index, 'payFlag']}>
                <Switch
                  checkedChildren="是"
                  unCheckedChildren="否"
                  disabled={pageType == 'detail' ? true : disabled ? true : disabledFlag ? false : true}
                  checked={record?.payFlag == '1'}
                  onChange={(checked: boolean, _event: any) => {
                    let paymenList: Record<string, any>[] = formName?.getFieldValue('processList');
                    paymenList[index]['payFlag'] = checked ? '1' : '0';
                    paymenList[index]['payType'] = checked ? 2 : 5;
                    paymenList[index]['capitalDir'] = checked ? paymenList[index]['capitalDir'] : 2;
                    paymenList[index]['payNum'] = checked ? paymenList[index]['payNum'] : 0;
                    paymenList[index]['paySum'] = checked ? paymenList[index]['paySum'] : 0;
                    formName?.setFieldsValue({
                      processList: paymenList,
                    });
                  }}
                />
              </Form.Item>
            );
          }
        },
      },
      {
        title: '支付方式',
        dataIndex: 'payType',
        key: 'payType',
        visible: true,
        width: 180,
        render: (text: any, record: any, index: any) => {
          if (pageType == 'detail') {
            return (
              <Form.Item name={['processList', index, 'payType']}>
                <span>
                  {text == '0'
                    ? '一次性支付'
                    : text == '1'
                    ? '预付款'
                    : text == '2'
                    ? '进度款'
                    : text == '3'
                    ? '尾款'
                    : text == '4'
                    ? '其他方式'
                    : text == '5'
                    ? '无款项'
                    : '--'}
                </span>
              </Form.Item>
            );
          } else {
            return (
              <Form.Item
                name={['processList', index, 'payType']}
                rules={[
                  {
                    required: record?.payFlag,
                    message: '请选择款项',
                  },
                ]}
              >
                <Select
                  placeholder="请选择"
                  // showArrow={!pamTypeKeys?.includes(text) ? true : false}
                  showArrow={false}
                  // disabled={!pamTypeKeys?.includes(text) ? false : true}
                  disabled={true}
                  // allowClear={!pamTypeKeys?.includes(text) ? true : false}
                >
                  <Select.Option key={0} value={0} style={{ display: 'none' }}>
                    一次性支付
                  </Select.Option>
                  <Select.Option key={1} value={1} style={{ display: 'none' }}>
                    预付款
                  </Select.Option>
                  <Select.Option key={2} value={2}>
                    进度款
                  </Select.Option>
                  <Select.Option key={3} value={3} style={{ display: 'none' }}>
                    尾款
                  </Select.Option>
                  <Select.Option key={4} value={4} style={{ display: 'none' }}>
                    其他方式
                  </Select.Option>
                  <Select.Option key={5} value={5}>
                    无款项
                  </Select.Option>
                </Select>
              </Form.Item>
            );
          }
        },
      },

      {
        title: '支付金额（元）',
        dataIndex: 'paySum',
        key: 'paySum',
        visible: true,
        width: 180,
        render: (text: string | any, _record: any, index: any) => {
          if (pageType == 'detail') {
            return (
              <Form.Item name={['processList', index, 'paySum']}>
                {/* <Tooltip title={text}> */}
                <span>{text ? priceFormat(text) : '0.00'}</span>
                {/* </Tooltip> */}
              </Form.Item>
            );
          } else {
            const disabled: boolean = _record?.payFinishSum && _record?.payFinishSum > 0 ? true : false;
            return (
              <Form.Item
                name={['processList', index, 'paySum']}
                rules={[
                  {
                    required: true,
                    message: '请输入',
                  },
                  {
                    pattern: RegularExpression?.two2FloatNumber,
                    message: '金额，最多四位小数',
                  },
                ]}
              >
                <InputNumber
                  step="0.0001"
                  placeholder="请输入"
                  disabled={
                    pageType == 'detail' ? true : disabled ? true : _record?.payType == '0' || _record?.payType == '4' || _record?.payType == '5' ? true : false
                  }
                  onChange={(value: any) => {
                    const sumIntax: number = formName?.getFieldValue('sumInTax');
                    const paymenList: Record<string, any>[] = formName?.getFieldValue('processList');

                    let allPaySum: any = 0;
                    paymenList?.forEach((item: any) => {
                      // allPaySum +=  item?.paySum ? item?.paySum : 0;
                      allPaySum = float_add(allPaySum, item?.paySum ? item?.paySum : 0);
                    });

                    if (allPaySum > sumIntax) {
                      message.warning('金额不能超过合同金额，请核查！');
                      paymenList[index]['paySum'] = null;
                      paymenList[index]['payNum'] = 0;
                    } else if (sumIntax) {
                      const newPaymen = (value / sumIntax) * 100;

                      paymenList[index]['payNum'] = newPaymen.toFixed(2);
                    } else {
                      paymenList[index]['payNum'] = 0;
                      message.warning('请先输入合同金额！');
                    }
                    formName?.setFieldsValue({
                      processList: paymenList,
                    });
                  }}
                />
              </Form.Item>
            );
          }
        },
      },
      {
        title: '支付比例（%）',
        dataIndex: 'payNum',
        key: 'payNum',
        visible: true,
        width: 180,
        render: (text: string, record: any, index: any) => {
          return (
            <Form.Item name={['processList', index, 'payNum']}>
              {/* <Tooltip title={text}> */}
              <span>{text || '--'}</span>
              {/* </Tooltip> */}
            </Form.Item>
          );
          // if (pageType == 'detail') {
          //   return (
          //     <Form.Item name={['processList', index, 'payNum']}>
          //       {/* <Tooltip title={text}> */}
          //       <span>{text || '--'}</span>
          //       {/* </Tooltip> */}
          //     </Form.Item>
          //   );
          // } else {
          //   const disabled: boolean = record?.payFinishSum && record?.payFinishSum > 0 ? true : false;
          //   return (
          //     <Form.Item name={['processList', index, 'payNum']}>
          //       <InputNumber
          //         min={0}
          //         max={100}
          //         step="0"
          //         placeholder="请输入"
          //         disabled={
          //           pageType == 'detail' ? true : disabled ? true : record?.payType == '0' || record?.payType == '4' || record?.payType == '5' ? true : false
          //         }
          //         onChange={(value: any) => {
          //           const sumIntax: number = formName?.getFieldValue('sumInTax');
          //           const paymenList: Record<string, any>[] = formName?.getFieldValue('processList');

          //           let allPayNum: number = 0;
          //           paymenList?.forEach((item: any) => {
          //             allPayNum += item?.payNum ? item?.payNum : 0;
          //           });

          //           if (allPayNum > 100) {
          //             message.warning('支付比例不能超过 100%，请核查！');
          //             paymenList[index]['paySum'] = null;
          //             paymenList[index]['payNum'] = null;
          //           } else if (sumIntax) {
          //             const newPaymen = (sumIntax * value) / 100;
          //             paymenList[index]['paySum'] = newPaymen;
          //           } else {
          //             paymenList[index]['payNum'] = 0;
          //             message.warning('请先输入合同金额！');
          //           }
          //           formName?.setFieldsValue({
          //             processList: paymenList,
          //           });
          //         }}
          //       />
          //     </Form.Item>
          //   );
          // }
        },
      },
    ];
  }

  if (pageType == 'modify' && !special) {
    tableConfig.push({
      title: '已支付金额（元）',
      dataIndex: 'payFinishSum',
      key: 'payFinishSum',
      visible: true,
      width: 180,
      render: (text: string | any, _record: any, index: any) => {
        return <span>{text ? priceFormat(text) : '0.00'}</span>;
      },
    });
  }

  if (
    // paymentSty == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1001` &&
    pageType != 'detail'
  ) {
    tableConfig?.push({
      title: (
        <div style={{ width: '100%', textAlign: 'center' }}>
          <Button type="link" size="small" icon={<PlusCircleOutlined />} className="manageBtntTxtStyle" onMouseOut={onMouseOutBtn} onClick={addProgress}>
            添加
          </Button>
        </div>
      ),
      dataIndex: 'otherBtn',
      key: 'otherBtn',
      width: 100,
      fixed: 'right',
      render: (_text: any, record: any) => {
        let disabled: boolean = record?.payFinishSum && record?.payFinishSum > 0 ? true : false;
        let otherDisabled = false;
        if (formName?.getFieldValue('payStyle') == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002`) {
          otherDisabled = true;
          if (formName?.getFieldValue('processList')) {
            otherDisabled = formName?.getFieldValue('processList')?.length < 2 ? false : true;
          }
        }
        return (
          <div className="counterpoartDelBtnStyle">
            {(!pamTypeKeys?.includes(record?.payType) && !disabled) || otherDisabled ? (
              <Button
                type="link"
                size="small"
                // icon={<CloseCircleOutlined />}
                icon={<DeleteOutlined />}
                className={'manageBtntTxtStyle'}
                onMouseOut={onMouseOutBtn}
                onClick={() => {
                  delProgressPay(record);
                }}
              >
                删除
              </Button>
            ) : (
              <span style={{ cursor: 'no-drop' }}>--</span>
            )}
          </div>
        );
      },
    });
  }
  return tableConfig;
};

export { getMaterialTableConfig, getFieldConfig, getKeyNodesTableConfig };
